package netty.examples;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 接收数据然后处理
 *
 * @author zengjian
 * @create 2018-06-01 16:43
 * @since 1.0.0
 */
public class ReceivingDataHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        try {
            // 接收读取到的数据
            while (in.isReadable()) {
                System.out.println((char) in.readByte());
                System.out.flush();
            }
            // 响应数据缓存
            ctx.write(msg);
            // 刷新到对端
            ctx.flush();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
